<template>
  <view></view>
</template>

<script>
export default {
  name: 'ss-download',
  data() {
    return {
      downloading: false
    }
  },
  methods: {
    // 接收外部调用的下载方法
    download(item) {
      if (this.downloading) return

      this.downloading = true
      // item.type  // 1.预览图片，2.预览文件，3.预览视频

      // #ifdef H5
      this.downloadH5(item.src, item.name)
      // #endif

      // #ifdef MP-WEIXIN
      if (item.type === 1) {
        this.saveToPhotosAlbum(item.src)
      } else if (item.type === 2) {
        this.saveFile(item.src)
      } else {
        this.getDownVideo(item.src)
      }
      // #endif

      // #ifdef APP-PLUS
      this.saveFileToApp(item.src)
      // #endif

      setTimeout(() => {
        this.downloading = false
      }, 1000)
    },

    //H5下载图片到本地
    downloadH5(url, fileName) {
      uni.showLoading({
        title: '下载中...'
      })

      uni.downloadFile({
        url: url,
        success: (res) => {
          if (res.statusCode === 200) {
            const oA = document.createElement('a')
            oA.download = fileName || this.getFileNameFromUrl(url)
            oA.href = res.tempFilePath
            document.body.appendChild(oA)
            oA.click()
            oA.remove()

            uni.showToast({
              title: '下载成功',
              icon: 'success'
            })
          } else {
            this.showError('下载失败')
          }
        },
        fail: () => {
          this.showError('下载失败')
        },
        complete: () => {
          uni.hideLoading()
        }
      })
    },

    //微信小程序保存文档,不支持h5
    saveFile(url) {
      uni.showLoading({
        title: '下载中...'
      })

      uni.downloadFile({
        url: url,
        success: (res) => {
          if (res.statusCode !== 200) {
            this.showError('下载失败')
            return
          }

          const filePath = res.tempFilePath
          //保存到本地
          uni.saveFile({
            tempFilePath: filePath,
            success: (res) => {
              uni.openDocument({
                filePath: res.savedFilePath,
                fileType: this.getFileExtension(url),
                showMenu: true,
                success: () => {
                  uni.hideLoading()
                },
                fail: () => {
                  this.showError('打开文件失败')
                }
              })
            },
            fail: () => {
              this.showError('保存失败')
            }
          })
        },
        fail: () => {
          this.showError('下载失败')
        }
      })
    },

    //微信小程序保存视频
    getDownVideo(url) {
      uni.showLoading({
        mask: true,
        title: '下载中...'
      })

      const fileName = new Date().valueOf()
      const task = uni.downloadFile({
        url: url,
        // #ifdef MP-WEIXIN
        filePath: wx.env.USER_DATA_PATH + '/' + fileName + '.mp4',
        // #endif
        success: (res) => {
          if (res.statusCode !== 200) {
            this.showError('下载失败')
            return
          }

          const filePath = res.filePath
          uni.saveVideoToPhotosAlbum({
            filePath,
            success: () => {
              uni.showToast({
                title: '下载成功',
                icon: 'success'
              })

              // #ifdef MP-WEIXIN
              const fileMgr = wx.getFileSystemManager()
              fileMgr.unlink({
                filePath: wx.env.USER_DATA_PATH + '/' + fileName + '.mp4',
                success: () => {
                  console.log('临时文件删除成功')
                }
              })
              // #endif
            },
            fail: () => {
              this.showError('保存失败')
            },
            complete: () => {
              uni.hideLoading()
            }
          })
        },
        fail: () => {
          this.showError('下载失败，请稍后再试')
        }
      })

      task.onProgressUpdate(this.onProgress)
    },

    // 提示下载进度
    onProgress(res) {
      uni.showLoading({
        mask: true,
        title: res.progress ? '下载中' + res.progress + '%' : '下载中...'
      })
    },

    //微信小程序保存图片（此处也可用于app保存图片或视频）
    saveToPhotosAlbum(url) {
      // #ifdef APP-PLUS
      const showLoading = plus.nativeUI.showWaiting('正在下载')
      // #endif

      // #ifndef APP-PLUS
      uni.showLoading({
        title: '下载中...',
        mask: true
      })
      // #endif

      const task = uni.downloadFile({
        url: url,
        success: (res) => {
          const { statusCode, tempFilePath } = res
          if (statusCode === 200) {
            uni.saveImageToPhotosAlbum({
              filePath: tempFilePath,
              success: () => {
                uni.showToast({
                  title: '下载成功',
                  icon: 'success'
                })
              },
              fail: () => {
                this.showError('保存失败')
              },
              complete: () => {
                // #ifdef APP-PLUS
                plus.nativeUI.closeWaiting()
                // #endif

                // #ifndef APP-PLUS
                uni.hideLoading()
                // #endif
              }
            })
          } else {
            this.showError('下载失败')
            // #ifdef APP-PLUS
            plus.nativeUI.closeWaiting()
            // #endif

            // #ifndef APP-PLUS
            uni.hideLoading()
            // #endif
          }
        },
        fail: () => {
          this.showError('下载失败')
          // #ifdef APP-PLUS
          plus.nativeUI.closeWaiting()
          // #endif

          // #ifndef APP-PLUS
          uni.hideLoading()
          // #endif
        }
      })

      task.onProgressUpdate((res) => {
        // #ifdef APP-PLUS
        showLoading.setTitle('  正在下载' + res.progress + '%  ')
        // #endif

        // #ifndef APP-PLUS
        uni.showLoading({
          mask: true,
          title: '下载中' + res.progress + '%'
        })
        // #endif
      })
    },

    //移动端下载文件
    saveFileToApp(url) {
      // #ifdef APP-PLUS
      try {
        const dtask = plus.downloader.createDownload(url, {}, (d, status) => {
          if (status === 200) {
            uni.showToast({
              title: '下载完成',
              mask: false,
              duration: 1000
            })

            plus.runtime.openFile(
              plus.io.convertLocalFileSystemURL(d.filename),
              {},
              () => {
                console.log('打开成功')
              },
              () => {
                this.showError('打开文件失败')
              }
            )
          } else {
            this.showError('下载失败')
          }
        })

        dtask.start()
        let prg = 0
        const showLoading = plus.nativeUI.showWaiting('正在下载')

        dtask.addEventListener('statechanged', (task) => {
          switch (task.state) {
            case 1:
              showLoading.setTitle('正在下载')
              break
            case 2:
              showLoading.setTitle('已连接到服务器')
              break
            case 3:
              prg = parseInt((parseFloat(task.downloadedSize) / parseFloat(task.totalSize)) * 100)
              showLoading.setTitle('  正在下载' + prg + '%  ')
              break
            case 4:
              plus.nativeUI.closeWaiting()
              break
          }
        })
      } catch (err) {
        plus.nativeUI.closeWaiting()
        this.showError('下载失败')
      }
      // #endif
    },

    // 辅助方法
    showError(message) {
      uni.showToast({
        title: message,
        icon: 'none'
      })
    },

    getFileNameFromUrl(url) {
      if (!url) return 'download'
      const parts = url.split('/')
      return parts[parts.length - 1] || 'download'
    },

    getFileExtension(url) {
      if (!url) return 'pdf'
      const ext = url.split('.').pop().toLowerCase()

      const supportedTypes = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt']
      return supportedTypes.includes(ext) ? ext : 'pdf'
    }
  }
}

// 添加明确的导出
export { default as ssDownload } from './ss-download.vue'
</script>
